<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2019-07-03
  Time: 16:12
  To change this template use File | Settings | File Templates.
--%>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>2t生产计划</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <jsp:include page="${pageContext.request.contextPath }/resource_path.jsp" flush="true"/>
    <style type="text/css">
        .layui-table-click{
            background-color:#ddf2e9 !important;
        }
    </style>
</head>
<body>
    <div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="">首页</a>
            <a>
              <cite>生产计划</cite>
            </a>
        </span>
    </div>

    <%--新增/修改的弹框表格（暂时不用）--%>
    <div id="tableDiv" hidden="hidden">
        <br>
        <form class="layui-form" id="storageForm">
            <input id="id" name="id" hidden="hidden">
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="margin-left: 50px;">生产日期</label>
                    <div class="layui-input-inline" style="width:200px">
                        <input lay-verify="dateInProduced" class="layui-input" type="text" id="dateInProduced" name="dateInProduced" style="width:200px">
                    </div>
                </div>
                <div class="layui-inline">
                    <font style="color:red; font-size: 24px;">*</font>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="margin-left: 50px;">计划单号</label>
                    <div class="layui-input-inline" style="width:200px">
                        <input lay-verify="number" class="layui-input" type="text" id="number" name="number" style="width:200px">
                    </div>
                </div>
                <div class="layui-inline">
                    <font style="color:#ff2527; font-size: 24px;">*</font>
                </div>
            </div>
            <button class="layui-btn layui-btn-blue" lay-submit lay-filter="formSubmit" style="margin-left:150px">提交</button>
            &emsp;&emsp;&emsp;&emsp;
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
    </div>

    <%--导入的弹框表格--%>
    <div id="importDiv" hidden="hidden">
        <br>
        <form class="layui-form" id="importForm" enctype="multipart/form-data">
            <%-- <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="margin-left: 50px;">供应商名称</label>
	                <div class="layui-input-inline" style="width:200px">
						<select id="supplierId" name="supplier_id" class="layui-input" lay-verify="supplierId">
							<option value="">请选择供应商</option>
							<c:forEach items="${allSupplier }" var="supplier">
								<option value="${supplier.id }">${supplier.customer_name }</option>
							</c:forEach>
						</select><br>
					</div>
                </div>
                <div class="layui-inline">
                    <font style="color:red; font-size: 24px;">*</font>
                </div>
            </div> --%>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="margin-left: 50px;">仓库名称</label>
                    <div class="layui-input-inline" style="width:200px">
						<select id="warehouseId" name="warehouse_id" class="layui-input" lay-verify="warehouseId">
							<option value="">请选择仓库</option>
							<c:forEach items="${allWarehouse }" var="warehouse">
								<option value="${warehouse.id }">${warehouse.warehouse_name }</option>
							</c:forEach>
						</select><br>
					</div>
                </div>
                <div class="layui-inline">
                    <font style="color:#ff2527; font-size: 24px;">*</font>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="margin-left: 50px;">主机厂名称</label>
                    <div class="layui-input-inline" style="width:200px">
						<select id="clientId" name="client_id" class="layui-input" lay-verify="clientId">
							<option value="">请选择主机厂</option>
							<c:forEach items="${allClient }" var="client">
								<option value="${client.id }">${client.customer_name }</option>
							</c:forEach>
						</select><br>
					</div>
                </div>
                <div class="layui-inline">
                    <font style="color:#ff2527; font-size: 24px;">*</font>
                </div>
            </div>
            <div class="layui-form-item">
                <div class="layui-inline">
                    <label class="layui-form-label" style="margin-left: 50px;">生产计划</label>
                    <div class="layui-input-inline" style="width:200px">
                        <a id="test1" class="layui-btn layui-btn-blue"><i class="layui-icon">点击上传</i></a>
                    </div>
                </div>
            </div>
            <input type="hidden" lay-verify="fileName" id="fileName" name="fileName" value="">
            <button class="layui-btn layui-btn-blue" lay-submit lay-filter="formSubmit2" style="margin-left:150px">提交</button>
            &emsp;&emsp;&emsp;&emsp;
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </form>
    </div>

    <!-- 顶部搜索框 -->
    <div class="x-body">
        <div style="margin-bottom: 18px">
            <div class="layui-inline">
                <table>
                    <tr>
                        <td>
                            <div class="layui-form" style="width: 180px; margin-left: 10px">
                                <input class="layui-input" name="keyword01" id="keyword01" placeholder="请输入计划单号" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
                            </div>
                        </td>
                        <td>
                            <div class="layui-form" style="width: 180px; margin-left: 10px">
                                <input class="layui-input" name="keyword02" id="keyword02" placeholder="请选择计划日期" autocomplete="off" style="display: inline; width: 180px; margin-left: 10px">
                            </div>
                        </td>
                    </tr>
                </table>
            </div>
            <button class="layui-btn layui-btn-normal" data-type="reload" style="margin-left: 25px;"><i class="layui-icon layui-icon-search"></i>检索</button>
        </div>
        <!-- 头部按钮 -->
        <xblock>
            <!-- <button id="addTable" class="layui-btn layui-btn-warm"><i class="layui-icon layui-icon-add-circle-fine"></i>新增</button> -->
            <a id="download" href="${pageContext.request.contextPath }/excel/excelTemplate.do?title=2t生产计划模板" class="layui-btn layui-btn-blue"><i class="layui-icon layui-icon-file-b"></i>下载模板</a>
            <button id="import" class="layui-btn layui-btn-blue"><i class="layui-icon layui-icon-upload"></i>导入</button>
            <button id="shipmentsTask" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-add-circle-fine"></i>创建发货计划</button>
            <button id="deleteTable" class="layui-btn layui-btn-danger"><i class="layui-icon layui-icon-delete"></i>批量删除</button>
        </xblock>
        <!-- 生产计划列表 -->
        <table class="layui-hide" id="tableList" lay-filter="tableList"></table>
        <br/><br/>
        <!-- 生产计划详情列表 -->
        <table class="layui-hide" id="tableDetailList" lay-filter="tableDetailList"></table>
        <!-- 主表行操作 -->
        <script type="text/html" id="rowToolbar">
            <a class="layui-btn layui-btn-xs" lay-event="edit"><i class="layui-icon layui-icon-edit"></i>编辑</a>
        </script>
        <!-- 子表行操作 -->
        <script type="text/html" id="rowToolbar2">
            <a class="layui-btn layui-btn-xs" lay-event="delete"><i class="layui-icon layui-icon-del"></i>删除</a>
        </script>
    </div>

    <script type="text/javascript">
        var table;
        var planId;
        var status;
        layui.use(['table','layer','form','upload','laydate'], function() {
            table = layui.table;
            var layer = layui.layer;
            var form = layui.form;
            var upload = layui.upload;
            var laydate = layui.laydate;
            var $ = layui.jquery, active = {
                reload: function () {
                    var keyword01 = $("#keyword01").val();
                    var keyword02 = $("#keyword02").val();
                    table.reload('storageAreaTableId', {
                        method: 'get',
                        where: {"plan_number": keyword01, "start_date":keyword02}
	                    ,page: {
		                    curr: 1//重新从第 1 页开始
		                }
                    });
                    
                }
            }
            $('.layui-btn').on('click', function () {
                var type = $(this).data('type');
                active[type] ? active[type].call(this) : '';
            });
            
          	//日期控件
    		laydate.render({
            	elem: '#keyword02'
            });

            //指定允许上传的文件类型
            upload.render({
                elem: '#test1'
                ,url: '${pageContext.request.contextPath }/plan2tManager/uploadPlan2t.do'
                ,accept: 'file' //普通文件
                ,exts: 'xls|xlsx' //只允许上传Excel文件
                ,field:'file'
                ,method: 'POST'
                ,done: function(res){
                    console.log(res)
                    if (res.isSuccess >0) {
                        $('#fileName').val(res.fileName);
                        toastr.success('上传成功！');
                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                        },1000);
                    }else {
                        toastr.error('上传失败！');
                    }
                }
                ,error: function(){//请求异常回调
                    toastr.error('网络异常，请稍后重试！');
                }
            });
			
          	//监听复选框事件，被选中的行高亮显示
    	    table.on('checkbox(tableList)', function(obj){
    	    	if(obj.checked == true && obj.type == 'all'){
    		        //点击全选
    		        $('.layui-table-body table.layui-table tbody tr').addClass('layui-table-click');
    		    }else if(obj.checked == false && obj.type == 'all'){
    		        //点击全不选
    		        $('.layui-table-body table.layui-table tbody tr').removeClass('layui-table-click');
    		    }else if(obj.checked == true && obj.type == 'one'){
    		        //点击单行
    			    if(obj.checked == true){
    			          obj.tr.addClass('layui-table-click');
    			    }else{
    			          obj.tr.removeClass('layui-table-click');
    			    }
    		    }else if(obj.checked == false && obj.type == 'one'){
    		        //点击全选之后点击单行
    		        if(obj.tr.hasClass('layui-table-click')){
    		        	obj.tr.removeClass('layui-table-click');
    		        }
    		    }
    	    });
          
            /* 生产计划列表 */
            table.render({
                elem: '#tableList'
                ,url:'${pageContext.request.contextPath }/plan2tManager/list.do'
                ,title: '生产计划列表'
                ,id :'storageAreaTableId'
                ,limits:[10,20,30]
                ,cols: [[
                    {type: 'checkbox', fixed: 'left', },
                    {field:'', title:'序号', type:'numbers', align:'center'},
                    /* {field:'supplier_name', title:'供应商名称', align:'center'}, */
                    {field:'warehouse_name', title:'仓库名称', align:'center'},
                    {field:'client_name', title:'主机厂名称', align:'center'},
                    {field:'plan_number', title:'计划单号', align:'center'},
                    {field:'start_date', title:'计划日期', align:'center'},
                    {field:'user_name', title:'创建人', align:'center'},
                    {field:'create_date', title:'创建日期', align:'center'},
                    {field:'status1', title:'是否生成发货计划', align:'center',templet: function(d){
          	    		if (d.status1 == 0) {
        	    			return '未生成';
        				}else if(d.status1 == 1){
        					return '已生成';
        				}
                    }},
                   /*  {field:'status2', title:'是否生成补货计划', align:'center',templet: function(d){
          	    		if (d.status2 == 0) {
        	    			return '未生成';
        				}else if(d.status2 == 1){
        					return '已生成';
        				}
                    }} */
                    /* ,{fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar',width:100, align: 'center'} */
                ]]
                ,page: true
                ,done : function(){
                    $('th').css({
                        'background-color': '#009688', 'color': '#fff','font-weight':'bold',
                    })
                }
            });
            
          	//监听行单击事件(子表：生产计划详情)
	       	table.on('row(tableList)', function(obj){
	       		status = obj.data.status;
	       	  	table.render({
	       		    elem: '#tableDetailList'
	       		    ,url:'${pageContext.request.contextPath }/planDetail/list.do'
	       		    ,where:{planid: obj.data.id}
	       		    ,title: '产品的配件详情数据表'
	       		    ,id :'contentDetialTable'
	       		    ,limits:[10,20,30]
	       		    ,cols: [[
	       		    	{field:'left', title:'序号', sort: true, type:'numbers', width: 60},
	       		    	{field:'productName', title:'车种', align:'center', width: 130},
	                    {field:'productNumber', title:'车型', align:'center', width: 150},
	                    {field:'tsum', title:'SUM', align:'center'},
	                    {field:'t67', title:'06~07', align:'center'},
	                    {field:'t89', title:'08~09', align:'center'},
	                    {field:'t1011', title:'10~11', align:'center'},
	                    {field:'t1213', title:'12~13', align:'center'},
	                    {field:'t1415', title:'14~15', align:'center'},
	                    {field:'t1617', title:'16~17', align:'center'},
	                    {field:'t1819', title:'18~19', align:'center'},
	                    {field:'t2021', title:'20~21', align:'center'},
	                    {field:'t2223', title:'22~23', align:'center'},
	                    {field:'t01', title:'0~01', align:'center'},
	                    {field:'t23', title:'02~03', align:'center'},
	                    {field:'t45', title:'04~05', align:'center'},
	                    {fixed:'right',unresize: true, title:'操作', toolbar: '#rowToolbar2',width:150, align: 'center'}
	       		    ]]
	       		    ,page: true
	       		});
	       	});
            

            //新增
            $('#addTable').click(function(){
                layer.open({
                    type: 1 		//Page层类型
                    ,area: ['50%', '50%'] //宽  高
                    ,title: '新增'
                    ,shade: 0.1 	//遮罩透明度
                    ,shadeClose: true //点击遮罩关闭
                    ,maxmin: true //允许全屏最小化
                    ,anim: 1 		//0-6的动画形式，-1不开启
                    ,content: $('#tableDiv')
                    ,success: function () {
                        document.getElementById("storageForm").reset();
                        $("#id").val("")
                    }
                    ,end: function () {
                        var formDiv = document.getElementById('storageForm');
                        formDiv.style.display = '';
                        //layer.close(index);
                    }
                });
            });

            //导入
           $('#import').click(function(){
                layer.open({
                    type: 1 		//Page层类型
                    ,area: ['30%', '50%'] //宽  高
                    ,title: '导入生产计划'
                    ,shade: 0.1 	//遮罩透明度
                    ,shadeClose: true //点击遮罩关闭
                    ,maxmin: true //允许全屏最小化
                    ,anim: 1 		//0-6的动画形式，-1不开启
                    ,content: $('#importDiv')
                    ,success: function () {
                        document.getElementById("importForm").reset();
                    }
                    ,end: function () {
                        var formDiv = document.getElementById('importForm');
                        formDiv.style.display = '';
                        //layer.close(index);
                    }
                });
            }); 
           
         	//生产发货计划
           $('#shipmentsTask').click(function(obj){
        	   var rowData = table.checkStatus('storageAreaTableId');
               var data = rowData.data;
        	   if(data.length == 0){
        		   toastr.warning("请选择一条记录！");
        	   }else if(data.length > 1){
        		   toastr.warning("只能选择一条记录！");
        	   }else{
        		   if(data[0].status1 == 1){
        			   toastr.warning("已生成发货计划！");
        		   }else{
        			   $.ajax({
                           type:'post',
                           url:'${pageContext.request.contextPath }/plan2tManager/createShipmentsTask.do',
                           data:{"id":data[0].id},
                           dataType : "json",
                           success:function(data){
                               if(data>0){
                                   toastr.success("创建成功！");
                                   setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                       //关闭模态框
                                       // 父页面刷新
                                       window.location.reload();
                                   },1000);
                               }else{
                                   toastr.error("创建失败！");
                               }
                           }
                       })
        		   }
        	   }
            }); 
           
           $('#demandTask').click(function(obj){
        	   var rowData = table.checkStatus('storageAreaTableId');
               var data = rowData.data;
        	   if(data.length == 0){
        		   toastr.warning("请选择一条记录！");
        	   }else if(data.length > 1){
        		   toastr.warning("只能选择一条记录！");
        	   }else{
        		   if(data[0].status2 == 1){
        			   toastr.warning("已生成补货计划！");
        		   }else{
        			   $.ajax({
                           type:'post',
                           url:'${pageContext.request.contextPath }/plan2tManager/createDemandTask.do',
                           data:{"id":data[0].id},
                           dataType : "json",
                           success:function(data){
                               if(data>0){
                                   toastr.success("创建成功！");
                                   setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                       //关闭模态框
                                       // 父页面刷新
                                       window.location.reload();
                                   },1000);
                               }else{
                                   toastr.error("创建失败！");
                               }
                           }
                       })
        		   }
        	   }
            }); 
            //批量删除
            $('#deleteTable').click(function(obj){
                var rowData = table.checkStatus('storageAreaTableId');
                var data = rowData.data;
                var str = "";
                var sum = 0;
                if(data.length==0){
                    toastr.warning("请至少选择一条记录！");
                }else{
                    for(var i=0;i<data.length;i++){
                        str += data[i].id;
                        if(i != data.length-1){
                            str += ",";
                        }
                        if(data[i].status1 == 0 & data[i].status2 == 0){
                        	sum += 1;
                        }
                    }
                    if(sum == data.length){
                    	layer.confirm('确定删除吗？', function(index){
                            $.ajax({
                                type:'post',
                                url:'${pageContext.request.contextPath }/plan2tManager/delete.do',
                                data:{"ids":str},
                                dataType : "json",
                                success:function(data){
                                    if(data>0){
                                        toastr.success("删除成功！");
                                        setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                            //关闭模态框
                                            // 父页面刷新
                                            window.location.reload();
                                        },1000);
                                    }else{
                                        toastr.error("删除失败！");
                                    }
                                }
                            })
                            layer.close(index);
                        });
                    }else{
                    	toastr.warning("已生成任务不能删除！");
                    }
                }
            });

            //主表行操作
            table.on('tool(tableList)', function(obj){
                var data = obj.data;
                var checkStatus = table.checkStatus(obj.data.id);
                $('#id').val(obj.data.id);
                if(obj.event === 'edit'){
                    layer.open({
                        type: 1 		//Page层类型
                        ,area: ['50%', '50%'] //宽  高
                        ,title: '编辑'
                        ,shade: 0.1 	//遮罩透明度
                        ,maxmin: true //允许全屏最小化
                        ,anim: 1 		//0-6的动画形式，-1不开启
                        ,content: $('#tableDiv')
                        ,success: function () {
                            //回显表单数据
                            for(var i=0;i<Object.entries(data).length;i++) {
                                var id = '#' + Object.entries(data)[i][0];
                                var text = Object.entries(data)[i][1];
                                $(id).val(text);
                            }
                            form.render();
                        }
                        ,end: function () {
                            var formDiv = document.getElementById('storageForm');
                            formDiv.style.display = '';
                            layer.close(index);
                        }
                    });
                }
            });
            
            //子表行操作
            table.on('tool(tableDetailList)', function(obj){
                var data = obj.data;
                var checkStatus = table.checkStatus(obj.data.id);
                if(status == 0){
                	layer.confirm('确定删除吗？', function(index){
                        $.ajax({
                            type:'post',
                            url:'${pageContext.request.contextPath }/plan2tManager/delete.do',
                            data:{"ids":str},
                            dataType : "json",
                            success:function(data){
                                if(data>0){
                                    toastr.success("删除成功！");
                                    setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
                                        //关闭模态框
                                        // 父页面刷新
                                        window.location.reload();
                                    },1000);
                                }else{
                                    toastr.error("删除失败！");
                                }
                            }
                        })
                        layer.close(index);
                    });
                }else{
                	toastr.warning("已生成任务不能删除！");
                }
            });

            /**
             * 提交(新增/编辑)
             */
            form.on('submit(formSubmit)', function (data) {
                var title = "新增";
                var url = '${pageContext.request.contextPath}/plan2tManager/insert.do';
                var id = $.trim($("#id").val());
                if(id != "" && id != null && id != 'undefined'){
                    url = '${pageContext.request.contextPath}/plan2tManager/update.do';
                    title = "修改";
                }
                $.ajax({
                    url : url,
                    data: $("#storageForm").serialize(),
                    cache : false,
                    type : "post",
                }).done(
                    function(res) {
                        if (res > 0) {
                            toastr.success(title + '成功！');
                        }else{
                            toastr.error(title + '失败！');
                        }
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }
                ).fail(
                    function(res) {
                        toastr.error(title + '失败！');
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }
                )
                return false;
            });

            /**
             * 导入的提交
             */
            form.on('submit(formSubmit2)', function (data) {
                $.ajax({
                    url : '${pageContext.request.contextPath}/plan2tManager/importPlan2t.do',
                    data: $("#importForm").serialize(),
                    cache : false,
                    type : "post",
                }).done(
                    function(res) {
                        if (res > 0) {
                            toastr.success('导入成功！');
                        }else{
                            if(res == -1){
                            	toastr.error('产品名称或编号有误！');
                            }else{
                            	toastr.error('网络异常，请稍后重试！');
                            }
                        }
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }
                ).fail(
                    function(res) {
                        toastr.error('导入失败！');
                        setTimeout(function(){
                            location.reload();
                        },1000);
                    }
                )
                return false;
            });

            /**
             * 表单校验
             */
            form.verify({
                /* supplierId: function(value){
                    var str = value.replace(/\s+/g,"");
                    if(str == ''){
                        return '供应商名称不能为空';
                    }
                }, */
                clientId: function(value){
                    var str = value.replace(/\s+/g,"");
                    if(str == ''){
                        return '主机厂名称不能为空';
                    }
                },
                warehouseId: function(value){
                    var str = value.replace(/\s+/g,"");
                    if(str == ''){
                        return '仓库名称不能为空';
                    }
                },
                fileName: function(value){
                    var str = value.replace(/\s+/g,"");
                    if(str == ''){
                        return '请上传生产计划';
                    }
                },
            });
        });
        /*提示框样式*/
        toastrStyle()
    </script>
</body>
</html>
